<template>
  <view class="container">
    <view v-for="(category, index) in categories" :key="index" class="category">
      <view class="category-header">
        <image :src="loadUrl + category.image" mode="aspectFit" class="category-image"></image>
        <view class="header-text">
          <text class="category-title">{{ category.title }}</text>
          <text class="more" v-if="category.showMore">更多 ></text>
        </view>
      </view>
      <view class="category-content">
        <text class="category-description">{{ category.description }}</text>
        <button class="view-goods-button" @click="navigateToGoods(category.id)">查看商品</button>
      </view>
    </view>
    <view class="loading-text" v-if="loading">
      正在加载...
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      categories: [], // 猫分类及其商品列表
      loading: true, // 加载状态
      loadUrl: this.$loadUrl // 图片加载基础 URL
    };
  },
  methods: {
    fetchCategories() {
      this.$service({
        url: '/items/category/other', 
        method: 'GET'
      }).then(response => {
        if (response.code === 0) {
          this.categories = response.data.map(category => ({
            ...category,
            description: category.description || "" // 确保 description 属性存在
          }));
        }
        this.loading = false; // 数据加载完成
      }).catch(error => {
        console.error('获取分类数据失败', error);
        this.loading = false; // 数据加载完成（即使失败）
      });
    },
    navigateToGoods(categoryId) {
      uni.navigateTo({
        url: `/pages/goods/goods?categoryId=${categoryId}`
      });
    }
  },
  mounted() {
    // 调用 fetchCategories 方法来获取分类及其商品数据
    this.fetchCategories();
  }
};
</script>

<style scoped>
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
}

.category {
  margin-bottom: 30rpx;
  background-color: #ffffff;
  border-radius: 20rpx;
  padding: 20rpx;
  box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.1);
}

.category-header {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
  position: relative;
}

.category-image {
  height: 180rpx;
  border-radius: 10rpx;
  margin-right: 20rpx;
  object-fit: cover;
}

.header-text {
  flex-grow: 1;
}

.category-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.more {
  font-size: 24rpx;
  color: #007aff;
  position: absolute;
  right: 20rpx;
  top: 20rpx;
}

.category-content {
  text-align: center;
}

.category-description {
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;
}

.view-goods-button {
  margin-top: 20rpx;
  padding: 10rpx 20rpx;
  font-size: 28rpx;
  color: #ffffff;
  background-color: #007aff;
  border: none;
  border-radius: 10rpx;
  cursor: pointer;
}

/* 加载提示文字 */
.loading-text {
  text-align: center;
  font-size: 24rpx; /* 将字号改为适合的大小 */
  color: #666;
  padding: 16rpx 0; /* 适当的上下内边距 */
}
</style>
